﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HigLabo.Net;
using System.Net;
using System.Xml.Linq;

namespace HigLabo.WindowsAzure.RestService.SqlAzureManagement
{
    /// <summary>
    /// 
    /// </summary>
    public abstract class SqlAzureManagementServiceResult
    {
        /// <summary>
        /// 
        /// </summary>
        public HttpStatusCode StatusCode { get; private set; }
        /// <summary>
        /// 
        /// </summary>
        public String BodyText { get; private set; }
        /// <summary>
        /// 
        /// </summary>
        public XDocument BodyXml
        {
            get
            {
                return String.IsNullOrEmpty(BodyText) ? null : XDocument.Parse(BodyText);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        private Dictionary<String, String> _Header = new Dictionary<string, string>();
        /// <summary>
        /// 
        /// </summary>
        public Dictionary<String, String> Header { get { return _Header; } }
        /// <summary>
        /// 
        /// </summary>
        public String RequestID
        {
            get { return this.GetHeaderValue("x-ms-request-id"); }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        protected String GetHeaderValue(String key)
        {
            if (_Header.ContainsKey(key) == true)
            {
                return _Header[key];
            }
            return "";
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="response"></param>
        public virtual void SetResponseData(HttpResponse response)
        {
            var res = response;
            this.StatusCode = res.StatusCode;
            BodyText = res.BodyText;
            SetHeader(res);
            LoadBody();
        }
        /// <summary>
        /// 
        /// </summary>
        protected abstract void LoadBody();

        private void SetHeader(HttpResponse response)
        {
            foreach (var key in response.Headers.Keys)
            {
                _Header[key] = response.Headers[key];
            }
        }
    }
}
